#include <iostream>
#include <thread>
#include <chrono>   
#include <functional>
#include "LogService.hpp"

#define RESET        "\033[0m"

#define BLACK        "\033[30m"
#define RED          "\033[31m"
#define GREEN        "\033[32m"
#define YELLOW       "\033[33m"
#define BLUE         "\033[34m"
#define MAGENTA      "\033[35m"
#define CYAN         "\033[36m"
#define WHITE        "\033[37m"

#define BOLD_BLACK   "\033[1m\033[30m"
#define BOLD_RED     "\033[1m\033[31m"
#define BOLD_GREEN   "\033[1m\033[32m"
#define BOLD_YELLOW  "\033[1m\033[33m"
#define BOLD_BLUE    "\033[1m\033[34m"
#define BOLD_MAGENTA "\033[1m\033[35m"
#define BOLD_CYAN    "\033[1m\033[36m"
#define BOLD_WHITE   "\033[1m\033[37m"

#define BG_BLACK     "\033[48;5;0m"
#define BG_RED       "\033[48;5;1m"
#define BG_GREEN     "\033[48;5;2m"
#define BG_YELLOW    "\033[48;5;3m"
#define BG_BLUE      "\033[48;5;4m"
#define BG_MAGENTA   "\033[48;5;5m"
#define BG_CYAN      "\033[48;5;6m"
#define BG_WHITE     "\033[48;5;7m"


// 测试 Demo
void testLogService()
{
    // 获取日志服务单例
    using namespace yzhzc::log;
    LogService* logger = yzhzc::log::LogService::GetInstance();

    // 设置日志文件路径（按需修改路径）
    logger->setLogFilePaths(FileRule("./log/info",
                            TimeUnit::DAILY, 1, TimeUnit::WEEKLY, 1),   // 每天生成，最多保留 1 周
                            LogService::debug, LogService::info)        // 应用在 debug 和 info 日志级别
           .setLogFilePaths(FileRule("./log/warn", 
                            TimeUnit::DAILY, 1, TimeUnit::WEEKLY, 2),   // 每天生成，最多保留 2 周
                            LogService::warn)                           // 应用在 warn 日志级别
           .setLogFilePaths(FileRule("./log/error", 
                            TimeUnit::WEEKLY, 1, TimeUnit::DAILY, 30),  // 每周生成，最多保留 30 天
                            LogService::error, LogService::fatal)       // 应用在 error 和 fatal 日志级别
           .applyRules();    // 应用规则（初始化文件节点）


    // 测试日志输出
    log_debug("这是一条调试日志，数字：%d", 123);
    log_info("这是一条信息日志，浮点数：%.2f", 3.14);
    log_warn("这是一条警告日志，字符串：%s", "Hello, World!");
    log_error("这是一条错误日志，布尔值：%d", true);
    log_fatal("这是一条致命日志，十六进制：0x%x", 255);


    // 测试日志级别开关
    logger->setLevelSwitch(false, LogService::info, LogService::warn, LogService::error); // 关闭调试日志
    log_debug("测试日志级别开关：将关闭 info，warn，fatal 级别的日志");
    log_info("这条日志不应该打印出来");
    log_warn("这条日志不应该打印出来");
    log_error("这条日志不应该打印出来");
    log_fatal("测试日志级别开关结束，这条日志应该打印出来");
    logger->setLevelSwitch(true); // 打开所有日志

    // 测试多线程日志写入
    auto threadFunc = []() {
        for (int i = 0; i < 10; ++i) {
            log_info("log_info: %d", i);
            // log_debug("cout: %d", i);
        }
        };

    std::thread t1(threadFunc);
    std::thread t2(threadFunc);
    std::thread t3(threadFunc);
    std::thread t4(threadFunc);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}
void test(){
        // 测试多线程日志写入
        auto threadFunc = []() {
            for (int i = 0; i < 5; ++i) {
                log_info("cout: %d", i);
            }
            };
    
        std::thread t1(threadFunc);
        // std::thread t2(threadFunc);
        // std::thread t3(threadFunc);
        // std::thread t4(threadFunc);
        t1.join();
        // t2.join();
        // t3.join();
        // t4.join();
}

void func1() {
    // 打印次数
    const int iterations = 100;

    // 定义不同的持续时间变量
    std::chrono::duration<long long, std::nano> duration1, duration2, duration3;

    // 1. 使用 printf 打印的性能测试
    auto start1 = std::chrono::high_resolution_clock::now();  // 开始计时
    for (int i = 0; i < iterations; ++i) {
        printf("[INFO] [C:\\Users\\96241\\Desktop\\CycLog\\src\\main.cpp] [135] [2025-03-02 21:58:48] log_info test %d\n", i);  // 使用 printf 打印
    }
    auto end1 = std::chrono::high_resolution_clock::now();  // 结束计时
    duration1 = end1 - start1;  // 计算并存储时间差，单位为纳秒

    // 2. 使用 std::cout 打印的性能测试
    auto start2 = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < iterations; ++i) {
        std::cout << "[INFO] [C:\\Users\\96241\\Desktop\\CycLog\\src\\main.cpp] [135] [2025-03-02 21:58:48] log_info test " << i << std::endl;  // 使用 std::cout 打印
    }
    auto end2 = std::chrono::high_resolution_clock::now();
    duration2 = end2 - start2;

    // 3. 使用 log_info 打印的性能测试
    auto start3 = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < iterations; ++i) {
        log_info("log_info test %d", i);  // 使用 log_info 打印
    }
    auto end3 = std::chrono::high_resolution_clock::now();
    duration3 = end3 - start3;

    // 输出所有结果
    std::cout << "=== 性能测试结果 ===" << std::endl;
    std::cout << "printf 耗时:    " << duration1.count() << " 纳秒 (平均: " << duration1.count() / iterations << " 纳秒/次)" << std::endl;
    std::cout << "std::cout 耗时: " << duration2.count() << " 纳秒 (平均: " << duration2.count() / iterations << " 纳秒/次)" << std::endl;
    std::cout << "log_info 耗时:  " << duration3.count() << " 纳秒 (平均: " << duration3.count() / iterations << " 纳秒/次)" << std::endl;
}

// 修改 test_function，使用 std::function 显式指定类型
void test_function(int iterations, std::function<void(int)> print_func, std::vector<std::chrono::nanoseconds>& durations) {
    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < iterations; ++i) {
        print_func(i);
    }
    auto end = std::chrono::high_resolution_clock::now();
    durations.push_back(end - start);
}

void func11() {
    // 打印次数
    const int iterations = 1000;
    const int num_threads = 4;

    // 存储每种打印方式的时间
    std::vector<std::chrono::nanoseconds> printf_durations;
    std::vector<std::chrono::nanoseconds> cout_durations;
    std::vector<std::chrono::nanoseconds> log_info_durations;

    // 定义三种打印方式的函数
    auto printf_func = [](int i) {
        printf("[INFO] [C:\\Users\\96241\\Desktop\\CycLog\\src\\main.cpp] [135] [2025-03-02 21:58:48] log_info test %d\n", i);
    };
    auto cout_func = [](int i) {
        std::cout << "[INFO] [C:\\Users\\96241\\Desktop\\CycLog\\src\\main.cpp] [135] [2025-03-02 21:58:48] log_info test " << i << "\n";
    };
    auto log_info_func = [](int i) {
        log_info("log_info test %d", i);
    };

    // 测试 log_info
    {
        std::vector<std::thread> threads;
        for (int i = 0; i < num_threads; ++i) {
            threads.emplace_back(test_function, iterations, log_info_func, std::ref(log_info_durations));
        }
        for (auto& t : threads) {
            t.join();
        }
    }

    // 测试 printf
    {
        std::vector<std::thread> threads;
        for (int i = 0; i < num_threads; ++i) {
            threads.emplace_back(test_function, iterations, printf_func, std::ref(printf_durations));
        }
        for (auto& t : threads) {
            t.join();
        }
    }

    // 测试 std::cout
    {
        std::vector<std::thread> threads;
        for (int i = 0; i < num_threads; ++i) {
            threads.emplace_back(test_function, iterations, cout_func, std::ref(cout_durations));
        }
        for (auto& t : threads) {
            t.join();
        }
    }



    // 汇总结果
    auto summarize = [](const std::string& name, const std::vector<std::chrono::nanoseconds>& durations) {
        auto min_time = *std::min_element(durations.begin(), durations.end());
        auto max_time = *std::max_element(durations.begin(), durations.end());
        std::cout << name << " 最快耗时: " << min_time.count() << " 纳秒, " << " 最慢耗时: " << max_time.count() << " 纳秒"<< std::endl;
    };

    std::cout << "=== 性能测试结果(迭代次数:" << iterations << ", 线程数:" << num_threads << ") ===" << std::endl;
    summarize("printf   : ", printf_durations);
    summarize("std::cout: ", cout_durations);
    summarize("log_info : ", log_info_durations);
}



int main()
{
    try {
        // func11();
        testLogService();
    }
    catch (const std::exception& e) {
        std::cerr << "测试失败，异常信息：" << e.what() << std::endl;
        return 1;
    }

    return 0;
}